/*!
 * Page: pages/information/detail/Detail
 * License: MIT
 * Created: 2019-11-09 17:03
 */
const REG_BODY = /<body[^>]*>([\s\S]*)<\/body>/
import { informationApi } from '/api/information'
import { GlobalData } from '/store/state'
import { $event, $utils } from '/utils'
import { checkAuth } from '/store/actions'

Page({
  data: {
    isFullScreen: GlobalData.isFullScreen,
    infos: {} as any,
    id: 0,
    navigationHeight: GlobalData.navigationHeight,
    comment: [] as any[],
    isLastpage: false,
    //点击锁
    click: false,
    //评论是否执行
    isLoading: false,
    access: GlobalData.access,
    imageUrls: [] as any[],
    isShowImage: false,
    current: 0,
  },
  onLoad(query: any) {
    let id = +query.id
    if (query.scene) {
      const scene = $utils.parseQueryString(query.scene)
      id = +scene.id
    }
    this.setData({
      isFullScreen: GlobalData.isFullScreen,
      id,
    })
    $event.on('after:changeFeedList', this, () => {
      this.getComment()
    })
  },
  onShow() {
    wx.showLoading({ title: '加载中' })
    this.getInfo()
    $event.on('after:boot', this, () => {
      this.getBoot()
    })
    this.getBoot()
    this.getComment()
    wx.hideLoading()
  },
  onPullDownRefresh() {
    this.getInfo()
    this.getComment()
    wx.stopPullDownRefresh()
  },
  onReachBottom() {
    this.onLoadmore()
  },
  onShareAppMessage() {
    this.setData({
      share: true,
    })
    return {
      path: $utils.getSharePath(),
    }
  },
  onPageScroll() {
    this.fixedTitle()
  },
  /** 是否滚动到标题 */
  fixedTitle() {
    const query = wx.createSelectorQuery().in(this)
    query.select('#title').boundingClientRect()
    query.selectViewport().scrollOffset()
    query.exec((res: any) => {
      this.setData({
        scrollTop: res[0] ? res[0].top < this.data.navigationHeight : true,
      })
    })
  },
  async getInfo() {
    const infos = await informationApi.getInformationDetail(this.data.id)
    infos.content = infos.content.replace(/<p/gi, '<p class="richText" ')
    infos.content = infos.content.replace(/<span/gi, '<span class="richText" ')
    infos.content = infos.content.replace(/<img/gi, '<img class="quill-image" ')
    infos.content = infos.content.replace(/<video/gi, '<video class="quill-video" ')

    infos.content = this.getBody(infos.content)
    this.setData({
      infos,
    })
  },
  async getComment(more = false) {
    const offset = more ? this.data.comment.length : 0
    const comment = await informationApi.getInformationComment(this.data.id, { offset })
    const isLastpage = comment.length < 15
    this.setData({
      comment: more ? [...this.data.comment, ...comment] : comment,
      isLastpage,
      isLoading: true,
    })
  },
  getBoot() {
    this.setData!({
      currencyName: GlobalData.currencyName,
      navigationHeight: GlobalData.navigationHeight,
      rechargeRatio: GlobalData.currency.settings['recharge-ratio'],
      access: GlobalData.access,
    })
  },
  async onLoadmore() {
    if (this.data.isLastpage) {
      wx.showToast({
        icon: 'none',
        title: '已没有更多',
      })
      return
    }
    wx.showLoading({ title: '加载中' })
    this.getComment(true)
    wx.hideLoading()
  },
  async collect() {
    if (this.data.click) return
    const infos = this.data.infos
    infos.favorites_count = infos.favorited ? infos.favorites_count - 1 : infos.favorites_count + 1
    infos.favorited = !infos.favorited
    this.data.click = true
    // 在此之前为了界面效果已经将数据反转,所以这里删除和添加反写
    infos.favorited
      ? await informationApi.collectInfo(infos.id)
      : await informationApi.deleteCollectInfo(infos.id)
    this.setData({
      infos,
      click: false,
    })
  },
  async comment() {
    await checkAuth()
    wx.showActionSheet({
      itemList: ['文字', '图片', '视频'],
      success(res) {
        switch (res.tapIndex) {
          case 0:
            wx.navigateTo({
              url: `/pages/publish/publish?about=infos`,
            })
            break

          case 1:
            wx.navigateTo({
              url: `/pages/publish/publish?type=image&about=infos`,
            })
            break

          case 2:
            wx.navigateTo({
              url: `/pages/publish/publish?type=video&about=infos`,
            })
            break
        }
      },
    })
  },
  async like() {
    if (this.data.click) return
    const infos = this.data.infos
    infos.likes_count = infos.liked ? infos.likes_count - 1 : infos.likes_count + 1
    infos.liked = !infos.liked
    this.setData({
      infos,
      click: true,
    })
    // 在此之前为了界面效果已经将数据反转,所以这里删除和添加反写
    infos.liked
      ? await informationApi.likeInfo(infos.id)
      : await informationApi.deleteLikeInfo(infos.id)
    this.setData({
      click: false,
    })
  },
  report() {
    const id = this.data.id
    wx.showActionSheet({
      itemList: ['举报'],
      success(res) {
        switch (res.tapIndex) {
          case 0:
            wx.navigateTo({
              url: `/pages/report/report?type=info&id=${id}`,
            })
            break
        }
      },
    })
  },
  getBody(content: any) {
    const result = REG_BODY.exec(content)
    if (result && result.length === 2) return result[1]
    return content
  },
  moreUrls(e: any) {
    const imageUrls = this.data.imageUrls
    imageUrls.push(e.detail.src)
    this.setData({ imageUrls })
  },
  btn(e: any) {
    for (let i = 0; i < this.data.imageUrls.length; i++) {
      if (e.detail.src == this.data.imageUrls[i]) {
        // wx.previewImage({
        //   urls: this.data.imageUrls,
        //   current: this.data.imageUrls[i],
        // })
        this.setData({ isShowImage: true, current: i })
      }
    }
  },
  closeShowImage() {
    this.setData({ isShowImage: false })
  },
})
